import { exec } from 'child_process';

// get the vide link from req.query.link
export function getVideoLink(fake_link: string) {
    return fake_link.split(',')
            .map(x => String.fromCharCode(parseInt(x)))
            .reduce((pre, cur) => pre + cur);
}


// get the video source url
export function getVideoSource(video_link: string) {
    return new Promise((resolve, reject) =>{
        exec(`youtube-dl --no-playlist -f best -g ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(stdout);
        })
    })
}


// delete all videos on ftp server
export function deleteAllVideos() {
    return new Promise((resolve, reject) => {
        exec(`cd /var/ftp && rm -rf *`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(`${stdout} 
            ok, all the videos are deleted now , 
            it's much more clean , you can download more videos haha`);
        });
    })
}


// delete one video on ftp server by name
export function deleteOneVideo(videoName: string) {
    return new Promise((resolve, reject) => {
        exec(`cd /var/ftp && rm -rf ${videoName}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(`${stdout} 
                     ${videoName} is deleted successfully`);
        })
    })
}


// beautify video formats info
export function beautifyFormatsInfo(stdout: string, video_link: string) {
    let formatsArr = stdout.split('\n').slice(5);
    let audioN = formatsArr.filter((item) => item.indexOf('m4a') != -1).map((item) => parseInt(item.substring(0, 3)))[0];
    let bestVideoInfo = formatsArr.filter((item) => item.indexOf('mp4') != -1 && item.indexOf('video only') != -1).pop();
    let bestVideoP = bestVideoInfo && bestVideoInfo.substr(35, 5).trim();
    let bestVideoM = bestVideoInfo && bestVideoInfo.substring(bestVideoInfo.length - 9).replace(/,/, ' ').trim();
    let bestVideoN = parseInt(bestVideoInfo?bestVideoInfo.substring(0, 3):"");
    let audioVideoInfo = formatsArr.filter(item => item.indexOf('best') != -1);
    let audioVideoN = audioVideoInfo.map((item) => parseInt(item.substring(0, 3)))[0];
    return JSON.stringify({
        audioN,
        bestVideoN,
        bestVideoP,
        bestVideoM,
        audioVideoN,
        video_link
    });
}


// find video name from downloading stdout
export function findVideoNameFromStdout(stdout: string) {
    let videoName = stdout.split('\n').filter(x => x.indexOf('Destination') !== -1)[0].substring(23).trim();
    return videoName;
}

// find video size from downloading stdout
export function findVideoSizeFromStdout(stdout: string) {
    let size = stdout.substr(stdout.indexOf('100%') + 7, 9);
    return parseFloat(size.trim()) + ' ';
}
